<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.9.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2"><link rel="stylesheet" href="/css/main.css?v=7.1.1"><link rel="apple-touch-icon" sizes="180x180" href="/images/my-apple-touch-icon-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="32x32" href="/images/my-32x32-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="16x16" href="/images/my-16x16-next.png?v=7.1.1"><link rel="mask-icon" href="/images/my-logo.svg?v=7.1.1" color="#222"><script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script><meta name="description" content="通过一个三极管配合树莓派的 gpio 接口就实现对树莓派散热风扇的控制，使风扇可以根据 cpu 的温度停止或转动"><meta name="keywords" content="树莓派,风扇,GPIO,控制风扇,散热"><meta property="og:type" content="article"><meta property="og:title" content="树莓派折腾日记-自动控制风扇"><meta property="og:url" content="https://renshengjihe.cn/190713-PiTempCtrl.html"><meta property="og:site_name" content="dhd的博客"><meta property="og:description" content="通过一个三极管配合树莓派的 gpio 接口就实现对树莓派散热风扇的控制，使风扇可以根据 cpu 的温度停止或转动"><meta property="og:locale" content="zh-CN"><meta property="og:image" content="https://renshengjihe.cn/190713-PiTempCtrl/连线图.png"><meta property="og:image" content="https://renshengjihe.cn/190713-PiTempCtrl/引脚图.png"><meta property="og:image" content="https://renshengjihe.cn/190713-PiTempCtrl/效果图1.png"><meta property="og:image" content="https://renshengjihe.cn/190713-PiTempCtrl/效果图2.png"><meta property="og:image" content="https://renshengjihe.cn/190713-PiTempCtrl/实物图.jpg"><meta property="og:updated_time" content="2019-11-18T07:46:11.985Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="树莓派折腾日记-自动控制风扇"><meta name="twitter:description" content="通过一个三极管配合树莓派的 gpio 接口就实现对树莓派散热风扇的控制，使风扇可以根据 cpu 的温度停止或转动"><meta name="twitter:image" content="https://renshengjihe.cn/190713-PiTempCtrl/连线图.png"><link rel="canonical" href="https://renshengjihe.cn/190713-PiTempCtrl"><script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script><title>树莓派折腾日记-自动控制风扇 | dhd的博客</title><noscript><style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">dhd的博客</span><span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">对酒当歌，人生几何</h1></div><div class="site-nav-toggle"> <button aria-label="切换导航栏"><span class="btn-bar"></span><span class="btn-bar"></span><span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li></ul></nav></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://renshengjihe.cn/190713-PiTempCtrl.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="dhd"><meta itemprop="description" content="个人博客,分享一些C/C++ Linux 相关的学习笔记"><meta itemprop="image" content="/images/avatar.gif"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="dhd的博客"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">树莓派折腾日记-自动控制风扇</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建时间：2019-07-13 17:08:00" itemprop="dateCreated datePublished" datetime="2019-07-13T17:08:00+08:00">2019-07-13</time> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i></span> <span class="post-meta-item-text">更新于</span> <time title="修改时间：2019-11-18 15:46:11" itemprop="dateModified" datetime="2019-11-18T15:46:11+08:00">2019-11-18</time></span> <span class="post-category"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/树莓派/" itemprop="url" rel="index"><span itemprop="name">树莓派</span></a></span></span> <span class="post-comments-count"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i></span> <span class="post-meta-item-text">评论数：</span><a href="/190713-PiTempCtrl.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/190713-PiTempCtrl.html" itemprop="commentCount"></span></a></span> <span id="/190713-PiTempCtrl.html" class="leancloud_visitors" data-flag-title="树莓派折腾日记-自动控制风扇"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span class="leancloud-visitors-count"></span></span><div class="post-description">通过一个三极管配合树莓派的 gpio 接口就实现对树莓派散热风扇的控制，使风扇可以根据 cpu 的温度停止或转动</div></div></header><div class="post-body" itemprop="articleBody"><p>前段时间买了一只树莓派来玩，在上面配置了一些文件共享服务、闹钟等功能（这些功能后面会在博客写上），开启闹钟的第一天就发生了一个令人头疼的问题，我用的是 3b+ ,所以装了风扇，一晚上下来无数次被风扇的声音吵醒，第二天就把它关掉了。。。。</p><p>树莓派装上风扇后噪音会比较大，而且风扇不停地转动会增加耗电，通过一个三极管配合树莓派的 gpio 接口就可以实现对风扇的控制，像笔记本电脑一样，只有在 cpu 需要降温的时候风扇才会转动。</p><a id="more"></a><p>参考自 <a href="http://shumeipai.nxez.com/2017/07/13/raspberry-pi-to-achieve-temperature-monitoring-and-control-fan-cooling.html" target="_blank" rel="noopener">树莓派实验室</a></p><h3 id="材料清单"><a href="#材料清单" class="headerlink" title="材料清单"></a>材料清单</h3><ul><li>树莓派 x1</li><li>三极管 x1</li><li>风扇 x1</li><li>面包板 x1 (可选)</li><li>杜邦线若干</li></ul><h3 id="连线"><a href="#连线" class="headerlink" title="连线"></a>连线</h3><p>如图为电路连线图，VCC, GND, GPIO 分别对应树莓派的引脚</p><p><img src="/190713-PiTempCtrl/连线图.png" alt="连线图"></p><p>如图为树莓派引脚功能图，GPIO 选择树莓派上任意一个 GPIO 接口即可，正负极一定注意别接反了。</p><p><img src="/190713-PiTempCtrl/引脚图.png" alt="连线图"></p><h3 id="驱动代码"><a href="#驱动代码" class="headerlink" title="驱动代码"></a>驱动代码</h3><h4 id="依赖库安装"><a href="#依赖库安装" class="headerlink" title="依赖库安装"></a>依赖库安装</h4><p>使用下面的代码需首先安装 wiringPi 库。<br></p><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">git <span class="built_in">clone</span> git://git.drogon.net/wiringPi</span><br></pre></td></tr></table></figure><p></p><p>也可以到 <a href="http://wiringpi.com" target="_blank" rel="noopener">http://wiringpi.com</a> 进行下载</p><h4 id="控制风扇的代码"><a href="#控制风扇的代码" class="headerlink" title="控制风扇的代码"></a>控制风扇的代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python</span></span><br><span class="line"><span class="comment">#coding=utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> commands,time</span><br><span class="line"></span><br><span class="line">FAN_GPIO = <span class="number">15</span></span><br><span class="line">commands.getoutput(<span class="string">'sudo gpio mode '</span> + str(FAN_GPIO) + <span class="string">' out'</span> )</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    <span class="comment"># 获取当前 cpu 温度</span></span><br><span class="line">    tmpFile = open(<span class="string">'/sys/class/thermal/thermal_zone0/temp'</span>)</span><br><span class="line">    cpu_temp_raw = tmpFile.read()</span><br><span class="line">    tmpFile.close()</span><br><span class="line">    cpu_temp = round(float(cpu_temp_raw) / <span class="number">1000</span>, <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">print</span> cpu_temp</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 大于 50 度，开启风扇降温</span></span><br><span class="line">    <span class="keyword">if</span> cpu_temp &gt;= <span class="number">50.0</span> :</span><br><span class="line">        commands.getoutput(<span class="string">'sudo gpio write '</span> + str(FAN_GPIO) + <span class="string">' 0'</span>);</span><br><span class="line">    <span class="comment"># 小于 45 度，关闭风扇</span></span><br><span class="line">    <span class="keyword">if</span> cpu_temp &lt;= <span class="number">45.0</span> :</span><br><span class="line">        commands.getoutput(<span class="string">'sudo gpio write '</span> + str(FAN_GPIO) + <span class="string">' 1'</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 每 10s 检测一次</span></span><br><span class="line">    time.sleep(<span class="number">10</span>)</span><br></pre></td></tr></table></figure><h4 id="配置开机启动"><a href="#配置开机启动" class="headerlink" title="配置开机启动"></a>配置开机启动</h4><p>我使用了配置服务的方式实现的开机启动</p><p>在 <code>/etc/init.d/</code> 下新建文件 <code>temp_ctrl</code> 并给上执行权限</p><p>文件内容如下<br></p><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># /etc/init.d/temp-ctrl</span></span><br><span class="line"><span class="comment"># Default-Start: 	2 3 4 5</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">case</span> <span class="string">"<span class="variable">$1</span>"</span> <span class="keyword">in</span></span><br><span class="line">    start)</span><br><span class="line">        <span class="built_in">echo</span> <span class="string">"start temp ctrl"</span></span><br><span class="line">        nohup /home/pi/gpio/fenshan.py &amp;</span><br><span class="line">        ;;</span><br><span class="line">    stop)</span><br><span class="line">        <span class="built_in">echo</span> <span class="string">"stop temp ctrl"</span></span><br><span class="line">        <span class="built_in">kill</span> $(ps aux | grep -m 1 <span class="string">'python /home/pi/gpio/fenshan.py'</span> | awk <span class="string">'&#123; print $2 &#125;'</span>)</span><br><span class="line">        ;;</span><br><span class="line">    *)</span><br><span class="line">        <span class="built_in">echo</span> <span class="string">"Usage : service temp-ctrl start/stop"</span></span><br><span class="line">        <span class="built_in">exit</span> 1</span><br><span class="line">        ;;</span><br><span class="line"><span class="keyword">esac</span></span><br><span class="line"><span class="built_in">exit</span> 0</span><br></pre></td></tr></table></figure><p></p><p>在 <code>/etc/rc.local</code> 中 <code>exit 0</code> 之前添加一行<br></p><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/etc/init.d/temp_ctrl start</span><br><span class="line"></span><br><span class="line"><span class="built_in">exit</span> 0</span><br></pre></td></tr></table></figure><p></p><h3 id="最终效果"><a href="#最终效果" class="headerlink" title="最终效果"></a>最终效果</h3><h4 id="程序执行的效果"><a href="#程序执行的效果" class="headerlink" title="程序执行的效果"></a>程序执行的效果</h4><p><img src="/190713-PiTempCtrl/效果图1.png" alt="连线图"></p><h4 id="通过服务的方式开启与关闭"><a href="#通过服务的方式开启与关闭" class="headerlink" title="通过服务的方式开启与关闭"></a>通过服务的方式开启与关闭</h4><p><img src="/190713-PiTempCtrl/效果图2.png" alt="连线图"></p><h4 id="连线实物图"><a href="#连线实物图" class="headerlink" title="连线实物图"></a>连线实物图</h4><p><img src="/190713-PiTempCtrl/实物图.jpg" alt="连线图"></p></div><footer class="post-footer"><div class="post-tags"> <a href="/tags/树莓派/" rel="tag"># 树莓派</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/190629-CppInheritance.html" rel="next" title="C++继承、多态与虚表分析"><i class="fa fa-chevron-left"></i> C++继承、多态与虚表分析</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"> <a href="/190721-PiLedShowIp.html" rel="prev" title="树莓派折腾日记-数码管显示 ip 地址">树莓派折腾日记-数码管显示 ip 地址<i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span><span class="sidebar-toggle-line sidebar-toggle-line-middle"></span><span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap"> 站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><p class="site-author-name" itemprop="name">dhd</p><div class="site-description motion-element" itemprop="description">个人博客,分享一些C/C++ Linux 相关的学习笔记</div></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">16</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/"><span class="site-state-item-count">7</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/"><span class="site-state-item-count">8</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="mailto:donghaodong555@foxmail.com" title="E-Mail &rarr; mailto:donghaodong555@foxmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a></span></div></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#材料清单"><span class="nav-number">1.</span> <span class="nav-text">材料清单</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#连线"><span class="nav-number">2.</span> <span class="nav-text">连线</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#驱动代码"><span class="nav-number">3.</span> <span class="nav-text">驱动代码</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#依赖库安装"><span class="nav-number">3.1.</span> <span class="nav-text">依赖库安装</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#控制风扇的代码"><span class="nav-number">3.2.</span> <span class="nav-text">控制风扇的代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置开机启动"><span class="nav-number">3.3.</span> <span class="nav-text">配置开机启动</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最终效果"><span class="nav-number">4.</span> <span class="nav-text">最终效果</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#程序执行的效果"><span class="nav-number">4.1.</span> <span class="nav-text">程序执行的效果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通过服务的方式开启与关闭"><span class="nav-number">4.2.</span> <span class="nav-text">通过服务的方式开启与关闭</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#连线实物图"><span class="nav-number">4.3.</span> <span class="nav-text">连线实物图</span></a></li></ol></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2019</span><span class="with-love" id="animate"><i class="fa fa-user"></i></span> <span class="author" itemprop="copyrightHolder">dhd</span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i></div></div><script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script><script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/lib/canvas-nest/canvas-nest.min.js"></script><script src="/lib/jquery/index.js?v=2.1.3"></script><script src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script src="/js/utils.js?v=7.1.1"></script><script src="/js/motion.js?v=7.1.1"></script><script src="/js/affix.js?v=7.1.1"></script><script src="/js/schemes/pisces.js?v=7.1.1"></script><script src="/js/scrollspy.js?v=7.1.1"></script><script src="/js/post-details.js?v=7.1.1"></script><script src="/js/next-boot.js?v=7.1.1"></script><script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script><script src="//unpkg.com/valine/dist/Valine.min.js"></script><script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'f6cPnWydCEaioX6iq6AoSBPz-gzGzoHsz',
    appKey: 'TRF9THIRqNFdQRvrCURnmfBG',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: '' || 'zh-cn'
  });
</script><script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz',
                'X-LC-Key': 'N3zDUUUGyqewKV2RLoozARF2',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script><script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script><script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script></body></html>